package net.xdclass.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.model.LoginUser;

import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

@Slf4j
public class JWTUtil {

    /**
     * token过期时间 7天
     */
    private static final long EXPIRE = 60 * 1000 * 60 * 24 * 7;

    /**
     * 秘钥
     */
    private static final String SECRET = "xdclass.net666";

    /**
     * 令牌前缀
     */
    private static final String TOKEN_PREFIX = "xdclass1024shop";

    /**
     * subject
     */
    private static final String SUBJECT = "xdclass";

    /**
     * 根据用户信息生成token
     * @param loginUser
     * @return
     */
    public static Map<String, String> geneJsonWebToken(LoginUser loginUser){

        Map<String, String> map = new HashMap<>();

        if (loginUser == null){
            throw new NullPointerException("loginUser对象为空");
        }

        Long userId = loginUser.getId();

        String token = Jwts.builder().setSubject(SUBJECT)
                .claim("head_img", loginUser.getHeadImg())
                .claim("id", loginUser.getId())
                .claim("name", loginUser.getName())
                .claim("mail", loginUser.getMail())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .signWith(SignatureAlgorithm.HS256, SECRET)
                .compact();

        token = TOKEN_PREFIX + token;

        map.put("token", token);
        map.put("EXPIRE", String.valueOf(EXPIRE));
        return map;
    }

    /**
     * 校验token
     * @param token
     * @return
     */
    public static Claims checkJWT(String token){
        try{
           final Claims claims = Jwts.parser().setSigningKey(SECRET)
                    .parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
                    .getBody();
            return claims;
        }catch (Exception e){
            log.info("token解密失败");
            return null;
        }
    }
}
